package com.shyroke.daydayzhuanweb.controller;

import com.google.gson.Gson;
import com.shyroke.daydayzhuanapi.constant.CommitConstant;
import com.shyroke.daydayzhuanapi.dto.BaiduCommitResp;
import com.shyroke.daydayzhuanapi.dto.MachineRewrite5118Resp;
import com.shyroke.daydayzhuanapi.entity.AppEntity;
import com.shyroke.daydayzhuanapi.entity.LabelEntity;
import com.shyroke.daydayzhuanapi.entity.ProjectEntity;
import com.shyroke.daydayzhuanapi.entity.SubjectEntity;
import com.shyroke.daydayzhuandao.respository.AppRepository;
import com.shyroke.daydayzhuandao.respository.LabelRepository;
import com.shyroke.daydayzhuandao.respository.SubjectRepository;
import com.shyroke.daydayzhuansvc.service.IProjectService;
import com.shyroke.daydayzhuansvc.service.impl.CommitService;
import com.shyroke.daydayzhuansvc.service.impl.OSSService;
import com.shyroke.daydayzhuansvc.util.CommonUtil;
import com.shyroke.daydayzhuansvc.util.OSSClientConstants;
import com.shyroke.daydayzhuansvc.util.R;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 类名 ：系统管理controller
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2019/2/21 12:49
 */
@Controller
@RequestMapping(value = "/admin/system")
public class SystemController {

    public static final String SITEMAP_FILENAME = "sitemap.xml";


    @Autowired
    private IProjectService projectService;

    @Autowired
    private OSSService ossService;

    @Autowired
    private CommitService commitService;

    @Autowired
    private LabelRepository labelRepository;

    @Autowired
    private SubjectRepository subjectRepository;

    @Value("${sitemap.path}")
    private String siteMapPath;

    @Value("${sitemap.name}")
    private String siteMapName;
    @Autowired
    private AppRepository appRepository;


    private Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 跳转到网站地图
     * @param model
     * @return
     */
    @RequestMapping(value = "sitemap")
    public ModelAndView siteMap (ModelAndView model){

        model.setViewName("admin/sitemap/list");

        return  model;
    }

    /**
     * 上传网站地图文件，必须xml格式
     * @return
     */
    @RequestMapping(value = "siteMapUpload")
    @ResponseBody
    public R siteMapUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request){

        if(file == null){
            return R.error("文件不能为空！");
        }

        try {
//            String path = request.getServletContext().getRealPath("/static/" + SITEMAP_FILENAME);
//            File savefile = new File(path);
//            FileUtils.copyInputStreamToFile(file.getInputStream(), savefile);
            ossService.deleteImg(OSSClientConstants.BUCKET_NAME,OSSClientConstants.SITEMAP_PATH+"sitemap.xml");
            ossService.uploadImg(file, OSSClientConstants.SITEMAP_PATH+"sitemap.xml");
        }catch (Exception e){
            logger.info(e.getMessage());
            return R.error("上传失败!");
        }

        return  R.ok("上传成功!");
    }

    /**
     * 获取网站地图oss上的地址
     * @return
     */
    @RequestMapping(value = "sitemappath.xml",produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public byte[] sitemapdesc(){
        byte[] result;
        try {
            InputStream in = ossService.getFileObj(OSSClientConstants.BUCKET_NAME,OSSClientConstants.SITEMAP_PATH+"sitemap.xml");

            result = IOUtils.toByteArray(in);
        }catch (Exception e){
            logger.info(e.getMessage());
            return null;
        }

        return result;
    }

    @RequestMapping(value = "updateSiteMap")
    @ResponseBody
    public R updateSiteMap() throws Exception{
        File file = new File(siteMapPath,siteMapName);
        if(!file.exists()){
            file.createNewFile();
        }

        String filePath = siteMapPath+siteMapName;

       //创建sitemap文档
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("urlset","http://www.sitemaps.org/schemas/sitemap/0.9");
        root.addNamespace("mobile","http://www.baidu.com/schemas/sitemap-mobile/1/");

        List<ProjectEntity> projectList = projectService.getProjectListByNoFollow();
        for(ProjectEntity project:projectList){
            Integer id = project.getId();
            Element urlEle = root.addElement("url");
            urlEle.addElement("loc").addText("https://www.daydayzhuan.com/article/"+id+"");
            urlEle.addElement("mobile:mobile").addAttribute("type","pc,mobile");
            urlEle.addElement("lastmod").addText(CommonUtil.getDateByFormat(project.getUpdateTime(),"yyyy-MM-dd"));
        }

        List<SubjectEntity> subjectList = subjectRepository.findAllByIsShowIsTrueOrderByIdDesc();
        for(SubjectEntity subject:subjectList){
            Integer subjectId = subject.getId();
            Element urlEle = root.addElement("url");
            urlEle.addElement("loc").addText("https://www.daydayzhuan.com/subject/"+subjectId);
            urlEle.addElement("mobile:mobile").addAttribute("type","pc,mobile");
            urlEle.addElement("lastmod").addText(CommonUtil.getDateByFormat(subject.getUpdateTime(),"yyyy-MM-dd"));
        }

        List<AppEntity> appList = appRepository.findByOffline(0);
        for(AppEntity app:appList){
            Integer appId = app.getId();
            Element urlEle = root.addElement("url");
            urlEle.addElement("loc").addText("https://www.daydayzhuan.com/app/"+appId);
            urlEle.addElement("mobile:mobile").addAttribute("type","pc,mobile");
            urlEle.addElement("lastmod").addText(CommonUtil.getDateByFormat(app.getCreateTime(),"yyyy-MM-dd"));
        }

        List<LabelEntity> labelList = labelRepository.findByIsShowTitle(0);
        for(LabelEntity label:labelList){
            Integer labelId = label.getId();
            ProjectEntity lastProject = projectService.getLastProjectByLabelId(labelId);
            if(lastProject == null){
                continue;
            }
            Element urlEle = root.addElement("url");
            urlEle.addElement("loc").addText("https://www.daydayzhuan.com/tag/"+label.getLabelName());
            urlEle.addElement("mobile:mobile").addAttribute("type","pc,mobile");
            urlEle.addElement("lastmod").addText(CommonUtil.getDateByFormat(lastProject.getCreateTime(),"yyyy-MM-dd"));
        }

        //输出格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //设置编码
        format.setEncoding("UTF-8");
        XMLWriter write;
        try {
            write = new XMLWriter(new FileOutputStream(filePath),format );
            write.write(root);
            write.flush();
            write.close();
        } catch (Exception e) {
            logger.info("写入sitemap文件异常",e);
            return R.error(e.getMessage());
        }


        return  R.ok("更新成功！");
    }


    @RequestMapping(value = "commit")
    @ResponseBody
    public R commit(Integer type,String url) throws Exception{

        if(type == null || StringUtils.isEmpty(url)){
            return R.error("提交类型或者文章url不能为空！");
        }

        if(CommitConstant.TYPE_BAIDU.equals(type)){
            //提交到百度
            List<String> urlList = new ArrayList<>();
            urlList.add(url);
            String result = commitService.commitBaidu(CommitConstant.BAIDU_COMMIT_URL,urlList);

            Gson gson = new Gson();
            BaiduCommitResp resp = gson.fromJson(result, BaiduCommitResp.class);

            StringBuffer sb = new StringBuffer();
            sb.append("成功数："+resp.getSuccess());
            sb.append("，不合法url列表："+ Arrays.toString(resp.getNot_valid()));
            sb.append("，剩余可提交数："+resp.getRemain());

            return R.ok(sb.toString());
        }else if(CommitConstant.TYPE_BAIDU_FAST.equals(type)){
            //提交到百度快速收录
            List<String> urlList = new ArrayList<>();
            urlList.add(url);
            String result = commitService.commitBaidu(CommitConstant.BAIDU_FAST_COMMIT_URL,urlList);
            return R.ok(result);
        }else if(CommitConstant.TYPE_BING.equals(type)){
            //提交到BING收录
            List<String> urlList = new ArrayList<>();
            urlList.add(url);
            String result = commitService.commitBing(CommitConstant.BING_COMMIT_URL,urlList);
            return R.ok(result);
        }

        return R.ok("success");
    }

    @RequestMapping(value = "wyc")
    @ResponseBody
    public R wyc(String content) throws Exception{

        if(StringUtils.isEmpty(content) || StringUtils.isEmpty(Jsoup.parse(content).text())){
            return R.error("内容不能为空！");
        }

        String machineContent = commitService.commit5118(content);
        String newContent = URLDecoder.decode(new Gson().fromJson(machineContent, MachineRewrite5118Resp.class).getData().replaceAll("%(?![0-9a-fA-F]{2})", "%25"),"utf-8");

        return R.ok("newContent",newContent);
    }
}
